package cn.io0288.blog2;

import cn.io0288.blog2.db.Users;
import cn.io0288.blog2.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Objects;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter pw = response.getWriter();
        HttpSession session = request.getSession();

        User testUser = new User(request.getParameter("email"), request.getParameter("password"));
        System.out.println(testUser);

        Users uuser = null;
        try {
            uuser = new Users(request.getParameter("email"));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        if (Objects.equals(uuser.user.upassword, testUser.upassword)) {
            session.setAttribute("uemail", testUser.uemail);
            session.setAttribute("uname", testUser.uname);
            System.out.println("登录成功, 200");
            request.setAttribute("msg", "登陆成功");
            response.sendRedirect(request.getContextPath()+"/");
        }else {
            System.out.println("登录失败, 500");
            request.getRequestDispatcher(request.getContextPath() + "/login.jsp").forward(request, response);
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter pw = response.getWriter();
        HttpSession session = request.getSession();

        // 是否登录
        if (session.getAttribute("uemail") != null) {
            request.setAttribute("msg", "已登录");
            response.sendRedirect(request.getContextPath()+"/");
        }else {
            request.getRequestDispatcher(request.getContextPath() + "/login.jsp").forward(request, response);
        }
    }
}